package com.yulan.bankback.controller.bank;


import com.yulan.bankback.aop.Authorization;
import com.yulan.bankback.entity.constant.RiskConstant;
import com.yulan.bankback.entity.model.bank.Coupon;
import com.yulan.bankback.entity.model.bank.Notice;
import com.yulan.bankback.entity.result.RetResponse;
import com.yulan.bankback.entity.result.RetResult;
import com.yulan.bankback.entity.vo.CardVo;
import com.yulan.bankback.entity.vo.MoneyDetailVo;
import com.yulan.bankback.entity.vo.UserVo;
import com.yulan.bankback.service.bank.BankService;
import com.yulan.bankback.service.bank.RedisService;
import com.yulan.bankback.service.bank.RiskService;
import com.yulan.bankback.util.IpUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;


@RestController
@RequestMapping("bank")
public class BankController {

    @Autowired
    private BankService bankService;

    @Autowired
    private RedisService redisService;


    @Autowired
    @Qualifier("baseThreadPool")
    private ThreadPoolExecutor executor;

    @Autowired
    private RiskService riskService;

    @Authorization({"admin", "bank_user"})
    @PostMapping("add")
    public String addOne(){
        return "success";
    }




    @Authorization({"admin", "bank_user"})
    @GetMapping("user_info")
    public RetResult getUserVo(@RequestParam("uid") String uid){
        if(StringUtils.isBlank(uid)) return RetResponse.makeErrRsp("uid不能为空");
        UserVo vo = bankService.getUserVo(uid);
        if(vo == null)
            return RetResponse.makeErrRsp("无此账号");

        return RetResponse.makeOKRsp(vo);
    }

    @Authorization({"admin", "bank_user"})
    @PostMapping("recharge")
    public RetResult recharge(String uid, String money, String type, String cardId){
        if(StringUtils.isBlank(uid)) return RetResponse.makeErrRsp("uid不能为空");
        bankService.recharge(uid, Double.valueOf(money), type, cardId);
        return  RetResponse.makeOKRsp();
    }

    @Authorization({"admin", "bank_user"})
    @GetMapping("/card/{uid}")
    public RetResult getAllCard(@PathVariable("uid") String uid){
        if(StringUtils.isBlank(uid)) return RetResponse.makeErrRsp("uid不能为空");
        return RetResponse.makeOKRsp(bankService.getUserAllCard(uid));
    }


    @Authorization({"admin", "bank_user"})
    @PostMapping("/card/")
    public RetResult getOneCard(String start, String end, String type, String uid, String cid){
        if(StringUtils.isBlank(uid)) return RetResponse.makeErrRsp("uid不能为空");
        if(StringUtils.isBlank(uid)) return RetResponse.makeErrRsp("cid不能为空");
        return RetResponse.makeOKRsp(bankService.getUserOneCardDetail(start, end, type, uid, cid));
    }

    @Authorization({"admin", "bank_user"})
    @PostMapping("/withdrawal")
    public RetResult withdrawal(HttpServletRequest request, String uid, String cid,
                                String money,String payPassword){
        if(StringUtils.isBlank(uid)) return RetResponse.makeErrRsp("uid不能为空");
        if(StringUtils.isBlank(cid)) return RetResponse.makeErrRsp("cid不能为空");
        if(StringUtils.isBlank(money)) return RetResponse.makeErrRsp("金额不能为空");
        if(StringUtils.isBlank(payPassword)) return RetResponse.makeErrRsp("支付密码不能为空");
        String res = bankService.withdrawal(uid, cid, Double.valueOf(money), payPassword);

        executor.execute(() ->{
            String ip = IpUtil.getIpAddr(request);
            if(!ip.matches(RiskConstant.IPV4_REGEX))
                return;
            riskService.checkRemoteWithdrawal(uid, ip);
        });

        return res.equals("success") ? RetResponse.makeOKRspMsg("提现成功") : RetResponse.makeErrRsp(res);
    }

    @Authorization({"admin", "bank_user"})
    @PostMapping("transfer")
    public RetResult transfer(HttpServletRequest request, String uid,
                              String phone, String money, String payPassword){
        if(StringUtils.isBlank(uid)) return RetResponse.makeErrRsp("uid不能为空");
        if(StringUtils.isBlank(phone)) return RetResponse.makeErrRsp("手机号不能为空");
        if(StringUtils.isBlank(money)) return RetResponse.makeErrRsp("转账金额不能为空");
        if(StringUtils.isBlank(payPassword)) return RetResponse.makeErrRsp("支付密码不能为空");
        String res = bankService.transfer(uid, phone, Double.valueOf(money), payPassword);

        executor.execute(() ->{
            String ip = IpUtil.getIpAddr(request);
            if(!ip.matches(RiskConstant.IPV4_REGEX))
                return;
            riskService.checkRemoteTransfer(uid, ip);
        });

        return res.equals("success") ? RetResponse.makeOKRspMsg("转账成功") : RetResponse.makeErrRsp(res);
    }

    @Authorization({"admin", "bank_user"})
    @GetMapping("money_detail/{uid}")
    public RetResult moneyDetail(@PathVariable("uid") String uid){
        if(StringUtils.isBlank(uid)) return RetResponse.makeErrRsp("uid不能为空");
        MoneyDetailVo vo = bankService.moneyDetail(uid);
        if(vo == null )
            return RetResponse.makeErrRsp("查询失败");
        return RetResponse.makeOKRsp(vo);
    }

    @Authorization({"admin", "bank_user"})
    @GetMapping("/coupon/list")
    public RetResult getAllCoupon(){
        List<Coupon> couponList =  bankService.getAllCoupon();
        if(couponList == null || couponList.isEmpty())
            return RetResponse.makeErrRsp("暂无优惠券");
        return RetResponse.makeOKRsp(couponList);
    }

    @Authorization({"admin", "bank_user"})
    @GetMapping("/coupon/{uid}")
    public  RetResult getUserAllCoupon(@PathVariable("uid") String uid) {
        List<Coupon> couponList = bankService.getUserAllCoupon(uid);
        if(couponList == null || couponList.isEmpty())
            return RetResponse.makeErrRsp("暂无优惠券");
        return RetResponse.makeOKRsp(couponList);
    }


    @Authorization({"admin", "bank_user"})
    @PostMapping("/coupon/conditions")
    public  RetResult getAllCouponByConditions(String start, String end, String type) {
        List<Coupon> couponList =  bankService.getCouponByConditions(start, end, type);
        if(couponList == null || couponList.isEmpty())
            return RetResponse.makeErrRsp("暂无优惠券");
        return RetResponse.makeOKRsp(couponList);
    }

    @Authorization({"admin", "bank_user"})
    @PostMapping("/coupon")
    public RetResult addCoupon(String type, String name, String start,
                               String end, String overDue, String discount, String count){
        if(StringUtils.isBlank(type)) return RetResponse.makeErrRsp("优惠券类型不能为空");
        if(StringUtils.isBlank(name)) return RetResponse.makeErrRsp("优惠券名称不能为空");
        if(StringUtils.isBlank(start)) return RetResponse.makeErrRsp("优惠券开始抢券时间类型不能为空");
        if(StringUtils.isBlank(end)) return RetResponse.makeErrRsp("优惠券结束抢券时间不能为空");
        if(StringUtils.isBlank(overDue)) return RetResponse.makeErrRsp("优惠券过期时间不能为空");
        if(StringUtils.isBlank(discount)) return RetResponse.makeErrRsp("优惠券折扣不能为空");
        if(StringUtils.isBlank(count)) return RetResponse.makeErrRsp("优惠券数量不能为空");

        String res = bankService.addCoupon(type, name, start, end, overDue,
                Double.valueOf(discount), Integer.valueOf(count));
        return res.equals("success") ?
                RetResponse.makeOKRspMsg("新增成功") :
                RetResponse.makeErrRsp(res);
    }

    @Authorization({"admin", "bank_user"})
    @PostMapping("/user_coupon")
    public RetResult addUserCoupon(String uid, String cid){
        if(StringUtils.isBlank(uid)) return RetResponse.makeErrRsp("用户ID不能为空");
        if(StringUtils.isBlank(cid)) return RetResponse.makeErrRsp("优惠券ID不能为空");
        String res = bankService.addUserCoupon(uid, cid);
        if(res.equals("success")) return RetResponse.makeOKRspMsg("抢券成功");

        return RetResponse.makeErrRsp(res);
    }

    @Authorization({"admin", "bank_user"})
    @PostMapping("/coupon/delete")
    public RetResult deleteUserCoupon(String uid, String cid){
        if(StringUtils.isBlank(uid)) return RetResponse.makeErrRsp("用户ID不能为空");
        if(StringUtils.isBlank(cid)) return RetResponse.makeErrRsp("优惠券ID不能为空");

        String res = bankService.deleteUserCoupon(uid, cid);
        if(res.equals("success")) return RetResponse.makeOKRspMsg("退订成功");

        return RetResponse.makeErrRsp(res);
    }


    @Authorization({"admin", "bank_user"})
    @GetMapping("/coupon/hot/{uid}")
    public RetResult getUserHotCoupon(@PathVariable("uid") String uid){
        if(StringUtils.isBlank(uid)) return RetResponse.makeErrRsp("用户ID不能为空");

        List<Coupon> res = bankService.getUserAllHotCardCoupon(uid);

        return res == null || res.isEmpty() ?
                RetResponse.makeErrRsp("没有该类型优惠券") :
                RetResponse.makeOKRsp(res);
    }

    @Authorization({"admin", "bank_user"})
    @GetMapping("/coupon/canteen/{uid}")
    public RetResult getUserCanteenCoupon(@PathVariable("uid") String uid){
        if(StringUtils.isBlank(uid)) return RetResponse.makeErrRsp("用户ID不能为空");

        List<Coupon> res = bankService.getUserAllCanteenCoupon(uid);

        return res == null || res.isEmpty() ?
                RetResponse.makeErrRsp("没有该类型优惠券") :
                RetResponse.makeOKRsp(res);
    }



    @Authorization({"admin", "bank_user"})
    @PostMapping("/hot_card")
    public RetResult rechargeHotCard(String money, String uid, String cid, String payPassword,  Double discount){
        if(StringUtils.isBlank(uid)) return RetResponse.makeErrRsp("用户ID不能为空");
        if(StringUtils.isBlank(money)) return RetResponse.makeErrRsp("充值金额不能为空");
        String success = bankService.rechargeHotCard(uid, cid, Double.valueOf(money), payPassword, discount);
        return success.equals("success") ? RetResponse.makeOKRspMsg("充值成功") : RetResponse.makeErrRsp(success);
    }

    @Authorization
    @PostMapping("/canteen_card")
    public RetResult rechargeCanteenCard(String money, String uid, String cid, String payPassword, Double discount){
        if(StringUtils.isBlank(uid)) return RetResponse.makeErrRsp("用户ID不能为空");
        if(StringUtils.isBlank(money)) return RetResponse.makeErrRsp("充值金额不能为空");
        String success = bankService.rechargeCanteenCard(uid, cid, Double.valueOf(money), payPassword, discount);
        return success.equals("success") ? RetResponse.makeOKRspMsg("充值成功") : RetResponse.makeErrRsp(success);
    }

    @Authorization({"admin", "bank_user"})
    @GetMapping("/hot_card/{uid}")
    public RetResult getUserHotCard(@PathVariable("uid") String uid){
        if(StringUtils.isBlank(uid)) return RetResponse.makeErrRsp("用户ID不能为空");
        CardVo cardVo = bankService.getUserHotCard(uid);
        return cardVo != null ?  RetResponse.makeOKRsp(cardVo) : RetResponse.makeErrRsp("用户不存在");
    }


    @Authorization({"admin", "bank_user"})
    @GetMapping("/canteen_card/{uid}")
    public RetResult getUserCanteenCard(@PathVariable("uid") String uid){
        if(StringUtils.isBlank(uid)) return RetResponse.makeErrRsp("用户ID不能为空");
        CardVo cardVo = bankService.getUserCanteenCard(uid);
        return cardVo != null ?  RetResponse.makeOKRsp(cardVo) : RetResponse.makeErrRsp("用户不存在");
    }

    @Authorization({"admin", "bank_user"})
    @PostMapping("/bind_card")
    public RetResult bindCard(HttpServletRequest request, String uid, String cid, String phone,
                              String code, String cardName){
        if(StringUtils.isBlank(uid)) return RetResponse.makeErrRsp("用户ID不能为空");
        if(StringUtils.isBlank(cid)) return RetResponse.makeErrRsp("银行卡号不能为空");
        if(StringUtils.isBlank(code)) return RetResponse.makeErrRsp("验证码不能为空");
        if(StringUtils.isBlank(cardName)) return RetResponse.makeErrRsp("银行卡名称不能为空");
        String targetCode = redisService.get(phone + "_msg");
        if(!StringUtils.equals(code, targetCode)) return RetResponse.makeErrRsp("验证码错误");
        String res = bankService.bindCard(uid, cid, cardName);

        executor.execute(() ->{
            String ip = IpUtil.getIpAddr(request);
            if(!ip.matches(RiskConstant.IPV4_REGEX))
                return;
            riskService.checkRemoteBindCard(uid, ip);
        });

        return res.equals("success") ? RetResponse.makeOKRspMsg("绑定成功") : RetResponse.makeErrRsp(res);
    }

    @Authorization({"admin", "bank_user"})
    @GetMapping("/notice")
    public RetResult getAllNotice(){
        return RetResponse.makeOKRsp(bankService.getAllNotice());
    }


    @Authorization({"admin", "bank_user"})
    @GetMapping("/notice/{id}")
    public RetResult getNoticeById(@PathVariable("id") String id){
        return RetResponse.makeOKRsp(bankService.getNoticeById(id));
    }

    @Authorization({"admin", "bank_user"})
    @PostMapping("/notice")
    public RetResult addNotice(String title, String publisher, String type, String content){
        if(StringUtils.isBlank(title)) return RetResponse.makeErrRsp("标题不能为空");
        if(StringUtils.isBlank(publisher)) return RetResponse.makeErrRsp("发布者不能为空");
        if(StringUtils.isBlank(type)) return RetResponse.makeErrRsp("公告类型不能为空");
        if(StringUtils.isBlank(content)) return RetResponse.makeErrRsp("内容不能为空");

        String res = bankService.addNotice(title, publisher, type, content);

        return StringUtils.equals(res, "success") ?
                RetResponse.makeOKRsp("添加成功") :
                RetResponse.makeErrRsp(res);
    }


    @Authorization({"admin", "bank_user"})
    @PutMapping("/notice")
    public RetResult updateNotice(String id, String title, String publisher, String type, String content){
        if(StringUtils.isBlank(id)) return RetResponse.makeErrRsp("id不能为空");
        if(StringUtils.isBlank(title)) return RetResponse.makeErrRsp("标题不能为空");
        if(StringUtils.isBlank(publisher)) return RetResponse.makeErrRsp("发布者不能为空");
        if(StringUtils.isBlank(type)) return RetResponse.makeErrRsp("公告类型不能为空");
        if(StringUtils.isBlank(content)) return RetResponse.makeErrRsp("内容不能为空");

        String res = bankService.updateNotice(id, title, publisher, type, content);

        return StringUtils.equals(res, "success") ?
                RetResponse.makeOKRsp("更新成功") :
                RetResponse.makeErrRsp(res);
    }

    @Authorization({"admin", "bank_user"})
    @PostMapping("/notice/search")
    public RetResult getNoticeByConditions(String title, String publisher, String type,String start, String end){
        if(StringUtils.isBlank(start) && StringUtils.isNotBlank(end))  return RetResponse.makeErrRsp("开始时间不能为空");
        if(StringUtils.isBlank(end) && StringUtils.isNotBlank(start))  return RetResponse.makeErrRsp("结束时间不能为空");
        List<Notice> res = bankService.getNoticeByConditions(title,publisher,type,start,end);
        return RetResponse.makeOKRsp(res);
    }

}





















